#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基础窗口类 - 提供通用的UI组件和工具方法
"""

import datetime
from json import dumps

from PySide6.QtWidgets import (
    QWidget, QHBoxLayout, QPushButton, QLabel, QTextEdit, QMessageBox
)


class BaseWindow(QWidget):
    """基础窗口类，提供通用功能"""
    
    def __init__(self):
        super().__init__()
        self.result_view = None  # 共享的结果显示区域
        
    def create_form_row(self, label_text: str, widget: QWidget) -> QHBoxLayout:
        """创建表单行布局"""
        layout = QHBoxLayout()
        label = QLabel(label_text)
        label.setMinimumWidth(100)  # 统一标签宽度
        layout.addWidget(label)
        layout.addWidget(widget)
        return layout
        
    def create_button(self, text: str, callback, tooltip: str = "") -> QPushButton:
        """创建按钮"""
        btn = QPushButton(text)
        btn.clicked.connect(callback)
        if tooltip:
            btn.setToolTip(tooltip)
        return btn
        
    def show_message(self, title: str, message: str, icon=QMessageBox.Information):
        """显示消息对话框"""
        QMessageBox(icon, title, message).exec()
        
    def show_warning(self, title: str, message: str):
        """显示警告对话框"""
        self.show_message(title, message, QMessageBox.Warning)
        
    def show_error(self, title: str, message: str):
        """显示错误对话框"""
        self.show_message(title, message, QMessageBox.Critical)
        
    def validate_required_fields(self, fields: dict, field_names: dict) -> bool:
        """验证必填字段"""
        empty_fields = []
        for field_key, field_obj in fields.items():
            if hasattr(field_obj, 'text') and not field_obj.text().strip():
                empty_fields.append(field_names.get(field_key, field_key))
            elif hasattr(field_obj, 'toPlainText') and not field_obj.toPlainText().strip():
                empty_fields.append(field_names.get(field_key, field_key))
                
        if empty_fields:
            self.show_warning("缺少信息", f"请填写: {', '.join(empty_fields)}")
            return False
        return True
        
    def create_result_view(self) -> QTextEdit:
        """创建结果输出区域"""
        result_view = QTextEdit()
        result_view.setReadOnly(True)
        result_view.setMaximumHeight(200)
        result_view.setStyleSheet("""
            QTextEdit {
                background-color: #f5f5f5;
                border: 1px solid #ddd;
                font-family: monospace;
            }
        """)
        return result_view
        
    def print_result(self, title: str, payload, result_view: QTextEdit = None):
        """将结果输出到文本区域"""
        if result_view is None:
            result_view = self.result_view
            
        if result_view is None:
            return
            
        # 添加时间戳
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        text = f"[{timestamp}] == {title} ==\n"
        
        # 如果payload是字典，尝试美化输出
        if isinstance(payload, dict):
            text += dumps(payload, ensure_ascii=False, indent=2)
        else:
            text += str(payload)
            
        # 如果有之前的输出，保留历史记录
        current_text = result_view.toPlainText()
        if current_text and not current_text.startswith("正在验证"):
            text = current_text + "\n\n" + text
            
        result_view.setPlainText(text)